#!/bin/bash
# OpenHarmony Build Manager (bl) - Bash 补全脚本
#
# 安装方法:
#   1. 复制到 /etc/bash_completion.d/ (全局):
#      sudo cp bl-completion.bash /etc/bash_completion.d/bl
#
#   2. 或添加到 ~/.bashrc (用户级):
#      echo 'source /path/to/bl-completion.bash' >> ~/.bashrc
#
#   3. 或在安装时自动复制到 ~/.local/share/bash-completion/completions/

_bl_completions() {
    local cur prev words cword
    _init_completion || return

    local commands="help list download build clean status config show-config branch remove set-max cron-enable cron-disable cron-status"
    local branch_subcmds="list add remove config show"

    # 获取已配置的分支列表
    _bl_get_branches() {
        local config_file="$HOME/openharmony/.bl_branches"
        if [ -f "$config_file" ]; then
            grep "^# Branch:" "$config_file" 2>/dev/null | sed 's/# Branch: //'
        fi
    }

    # 获取已下载的版本列表
    _bl_get_versions() {
        local code_dir="$HOME/openharmony/code_download"
        if [ -d "$code_dir" ]; then
            ls -1 "$code_dir" 2>/dev/null | grep -E '^.+_[0-9]{8}_[0-9]{6}$'
        fi
    }

    case "${prev}" in
        bl)
            # 第一级命令补全：命令 + 分支名
            local branches=$(_bl_get_branches)
            COMPREPLY=($(compgen -W "${commands} ${branches}" -- "${cur}"))
            return 0
            ;;
        download|-d)
            # download 后补全分支名
            COMPREPLY=($(compgen -W "$(_bl_get_branches)" -- "${cur}"))
            return 0
            ;;
        build|-b|remove)
            # build/remove 后补全版本号
            COMPREPLY=($(compgen -W "$(_bl_get_versions)" -- "${cur}"))
            return 0
            ;;
        clean)
            # clean 后补全分支名（可选）
            COMPREPLY=($(compgen -W "$(_bl_get_branches)" -- "${cur}"))
            return 0
            ;;
        branch)
            # branch 子命令补全
            COMPREPLY=($(compgen -W "${branch_subcmds}" -- "${cur}"))
            return 0
            ;;
        *)
            # 检查是否是 branch 的子命令上下文
            if [ "${words[1]}" = "branch" ]; then
                case "${words[2]}" in
                    remove|show|config)
                        COMPREPLY=($(compgen -W "$(_bl_get_branches)" -- "${cur}"))
                        return 0
                        ;;
                esac
            fi
            ;;
    esac

    # 默认补全命令
    COMPREPLY=($(compgen -W "${commands}" -- "${cur}"))
}

complete -F _bl_completions bl
